


// pages/dynamicForm/index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: defaultAvatarUrl,
    nickname: '匿名用户',
    anonymous: true,
    editid:false,
    openid:'',
    title:'',
    content:'',
    piclist: [],
    picCloudurl: []
  },
  async formSubmit(event) {
    wx.showLoading({
      title: '数据上传中',
    });
    let formcontent = event.detail.value.content.split('\n').join('&hc')
    let title = event.detail.value.title
    console.log(event.detail.value)
    let picCloudurl = await this.uploadImg(this.data.piclist)
    console.log(picCloudurl)
    let data = {
      content:formcontent,
      title:title,
      picCloudurl: picCloudurl,
      avatarUrl: this.data.avatarUrl,
      nickname: this.data.nickname,
      _openid:this.data.openid,
      time: new Date().getTime()
    }
      wx.hideLoading()
    await this.publishDymatic(data)
    
  },
  addpic: function () {
    let count = 3 - this.data.piclist.length-this.data.picCloudurl.length
    wx.chooseImage({
      count: count,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        let piclist = this.data.piclist.concat(res.tempFilePaths)
        //展示的图片路径
        this.setData({
          piclist: piclist
        })
      },
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  uploadImg(filepathlist) {
    let imgUrl = []
    return new Promise((resolve, reject) => {
      let len = filepathlist.length
      let timer=null
      for (let i = 0; i < filepathlist.length; i++) {
        let filePath = filepathlist[i]
        //生成云存储图片路径
        const name = Math.random() * 1000000;
        const cloudPath = name + filePath.match(/\.[^.]+?$/)[0]
        //上传至云存储
        wx.cloud.uploadFile({
          cloudPath, //云存储图片名字
          filePath, //临时路径
          success: res => {
            console.log('[上传图片] 成功：', res)
            imgUrl.push(res.fileID) //云存储图片路径,可以把这个路径存到集合，要用的时候再取出来
          },
          fail: e => {
            console.error('[上传图片] 失败：', e)
          },
          complete:(res)=>{
            console.log('完成:'+length)
            len--
          }
        });
      }
      let t=0
      	  // 关键部分
	  // 通过此部分来延续方法的时长，待到异步的回调执行完毕后则关闭
    // 以防万一，建议设定一个阈值，防止出现意外导致无限循环
	  timer = setInterval(() => {
      t++
       if(!len || len < -5000 || t>1500 ) {	// 只要len结束，将定时器清除
         console.log("同步结束");
         resolve(imgUrl)
         clearInterval(timer)	// 上传操作完成，消除阻塞
       }
     },1)	
    })
  },
  publishDymatic(data){
    if(this.data.editid==false){
    wx.cloud.init({env: 'cloud1-5glocnmp62950062'})
          wx.cloud.callFunction({
      name: 'publishDymatic',
      data: {data},
      success: function (res) {
        wx.showToast({
          title: '发布成功！',
          duration:2000,
          icon:'success',
          success:()=>{
            setTimeout(function(){
              wx.navigateBack({
              delta: 1,
            },2000)
            })
          }
        })
      },
      fail: function () {
        wx.showToast({
          title: '发布失败',
          icon: 'error',
        })
      },
      complete: res=>{
      }
    })
    }else{
      console.log(data)
      let picCloudurl = this.data.picCloudurl.concat(data.picCloudurl)
      wx.cloud.database().collection('dynamiclist').where({_id:this.data.editid}).update({
        data:{
          avatarUrl: data.avatarUrl,
          content: data.content,
          title:data.title,
          time: new Date().getTime(),
          picCloudurl: picCloudurl,
          nickname: data.nickname
        },
        success:(res)=>{
          console.log(res)
          wx.showToast({
            title: '更新成功！',
            duration:2000,
            icon:'success',
            success:()=>{
              setTimeout(function(){
                wx.navigateBack({
                delta: 1,
              },2000)
              })
            }
          })
        },
        fail:(res)=>{
          wx.showToast({
            title: '发生错误，请稍后再试',
            icon:'warning'
          })
        }
      })
    }

  },
  anonymousChange: function (e) {
    this.setData({
      anonymous: e.detail.value
    })
    if(!e.detail.value){
      let userInfo = wx.getStorageSync('userInfo'), avatar = wx.getStorageSync('AVATARURL'), nickname=wx.getStorageSync('NICKNAME')
      // if(!userInfo){
      //   this.setData({
      //     anonymous:true
      //   })
      //   wx.showToast({
      //     title: '您未填写个人信息，不可实名发布哦~',
      //     icon:'none'
      //   })
      //   return
      // }
      this.setData({
        avatarUrl: userInfo.avatar||avatar,
        nickname: userInfo.nickname||nickname
      })
    }else{
      this.setData({
        avatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
        nickname: '匿名用户'
      })
    }
  },

  onLoad: function (options) {
    if(options.editid){
      wx.cloud.database().collection('dynamiclist').where({_id:options.editid}).get({
        success: (res)=>{
          
          this.setData({
            editid: options.editid,
            avatarUrl:res.data[0].avatarUrl,
            content: res.data[0].content,
            nickname:res.data[0].nickname,
            picCloudurl:res.data[0].picCloudurl,
            title:res.data[0].title
          })
          console.log(res)
        }
      })
    }
    let userInfo = wx.getStorageSync('userInfo'), avatar = wx.getStorageSync('AVATARURL'), nickname=wx.getStorageSync('NICKNAME')
    this.setData({
      avatarUrl: userInfo.avatar||avatar,
      nickname: userInfo.nickname||nickname
    })
    this.setData({
      openid:wx.getStorageSync('OPENID')
    })
  },

  onReady: function () {

  },

  onShow: function () {

  },
})